<?php

namespace App\Modules\Admin\Services;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Rabc\AdminMenu;
use App\Modules\Admin\Entities\Rabc\AdminRole;
use App\Modules\Admin\Entities\Rabc\AdminRoleWithMenu;
use Illuminate\Support\Facades\DB;

class AdminRoleService extends BaseService
{
    public function __construct(AdminRole $adminRole)
    {
        $this->model = $adminRole;
        $this->modelRM = new AdminRoleWithMenu();
        $this->with = ['menus'];
    }

    public function lists(array $params) : array
    {
        return list_to_tree($this->model->where(function($query) use ($params){
            $search = $params['search'] ?? '';
            // 可以按照名称进行搜索
            if (!empty($search)) {
                $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
            }
            })->with(['menus'])->get()->toArray(),'role_id','parent_id');
    }

    public function getSelectLists($request) {
        $type =  $request->input('type', 0);
        $role_id =  $request->input('role_id', 0);
        if ($type==1) {
            return $this->model->getSelectLists();
        }else if ($type==2){
            $role_id =  $request->input('role_id', 0);

            if ($role_id!=0){
                $where = ['role_id'=>$role_id];
            }else{
                $where = [];
            }
            $arrayTree = $this->model->with(['menus'])->where($where)->first()->toArray();
            $first = ['menu_id','menu_id as value','parent_id','menu_name as  label','menu_name'];
            $menus = $arrayTree['menus'];
            $data_mune = list_to_tree($menus,'menu_id','parent_id','children');

            $data = $arrayTree['menu'] = $data_mune;

            return $data;
        }else{
            return $this->model->where(function($query) use ($request){
                $search = $request->input('search', '');
                // 可以按照名称进行搜索
                if (!empty($search)){
                    $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
                }
            })->with(['menus'])->orderBy($this->model->getKeyName(), 'ASC')->limit(100)->get();
        }

//        return $this->model->where(function($query) use ($request){
//            $search = $request->input('search', '');
//            // 可以按照名称进行搜索
//            if (!empty($search)){
//                $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
//            }
//        })->with(['menus'])->orderBy($this->model->getKeyName(), 'ASC')->limit(100)->get();
    }
    public function getSelectListsRole($request)
    {
        return $this->model->where(function($query) use ($request){
            $search = $request->input('search', '');
            // 可以按照名称进行搜索
            if (!empty($search)){
                $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
            }
        })->with(['menus'])->orderBy($this->model->getKeyName(), 'ASC')->limit(100)->get();
    }

    public function create(array $params)
    {
        DB::beginTransaction();
        try{
            parent::create($params); // TODO: Change the autogenerated stub

            $this->setMenuForRole($params);

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            $this->setError($e->getMessage());
            return false;
        }
    }

    public function update(array $params)
    {
        DB::beginTransaction();
        try{
            parent::update($params); // TODO: Change the autogenerated stub

            $this->setMenuForRole($params);

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            $this->setError($e->getMessage());
            return false;
        }
    }

    protected function setMenuForRole($params)
    {
        // 超级管理员角色不可编辑
        if (isset($params['menu_ids']) && $this->detail->{$this->model->getKeyName()} != 1){
            $menu_rules = $params['menu_ids'];

            $all_menus = AdminMenu::select('menu_id')->find($menu_rules)->toArray();//当前选中的菜单权限
            $new_all_menus = array_column($all_menus, 'menu_id', 'menu_id');
            $has_menus = $this->detail->menus->toArray();//当前已有的菜单权限
            $new_has_menus = array_column($has_menus, 'menu_id', 'menu_id');

            $primary_key = $this->model->getKeyName();
            /**
             * 添加的权限
             */
            $add_menus = get_array_diff($new_all_menus, $new_has_menus);
            if (!empty($add_menus)) {
                foreach ($add_menus as $menus) $this->model->grantMenus([
                    $primary_key => $this->detail->{$primary_key},
                    'menu_id' => $menus,
                ]);
            }

            /**
             * 要删除的权限
             */
            $delete_menus = get_array_diff($new_has_menus, $new_all_menus);
            if (!empty($delete_menus)) {
                foreach ($delete_menus as $menus) $this->model->deleteMenus([
                    $primary_key => $this->detail->{$primary_key},
                    'menu_id' => $menus,
                ]);
            }
        }
    }

    public function delete(array $params)
    {
        $primaryKey = $this->model->getKeyName();
        if (isset($params[$primaryKey]) && $params[$primaryKey] == 1){
            $this->setError('超管角色禁止删除！');
            return false;
        }

        // 如果是批量删除，那么移除Id
        if(isset($params['is_batch']) && $params['is_batch'] == 1){
            $ids_ary = explode(',', $params[$primaryKey]);
            if (in_array(1, $ids_ary)){
                $key = array_search(1, $ids_ary);
                unset($ids_ary[$key]);
                $params[$primaryKey] = implode(',', $ids_ary);
            }
        }
        return parent::delete($params); // TODO: Change the autogenerated stub
    }
}
